package com.bianmaba.spring.supports.data.repository.specification.condition.predicate.generator;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import java.lang.reflect.Method;

/**
 * LIKE
 * Created by cwx183898 on 2017/12/17.
 */
public class LikePredicateGenerator extends AbstractPredicateGenerator {

    private String before;
    private String after;

    public LikePredicateGenerator(String before, String after) {
        this.before = before;
        this.after = after;
    }

    protected Predicate createPredicate(CriteriaBuilder builder, Class clazz, Path path, Object[] datas) {

        try {
            Method method = getCreateMethod(builder);
            Predicate predicate = null;
            for (Object data : datas) {
                data = (before != null ? before : "") + data.toString() + (after != null ? after : "");
                if (predicate == null) {
                    predicate = (Predicate) method.invoke(builder, path, data);
                } else {
                    Predicate newPredicate = (Predicate) method.invoke(builder, path, data);
                    predicate = builder.or(predicate, builder.equal(path, data));
                }
            }
            return predicate;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    protected Method getCreateMethod(CriteriaBuilder builder) {
        try {
            Method method = builder.getClass().getMethod("like", Expression.class, String.class);
            return method;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

}